<template>
    <div class="pingding-records">
      <div class="records-header">
        <h2>创业能力评估档案记录</h2>
        <p class="subtitle" v-if="!isViewingOther">以下是您的创业能力评估历史记录</p>
        <p class="subtitle" v-else>以下是 {{userForm.xueshengxingming || userForm.xuehao}} 的创业能力评估历史记录</p>
        
        <!-- 导航按钮 -->
        <div class="navigation-buttons">
          <el-button type="primary" @click="goToHome" icon="el-icon-s-home">返回首页</el-button>
          <el-button type="info" @click="goToCenter" icon="el-icon-user">
            {{ isViewingOther ? '返回' : '返回个人中心' }}
          </el-button>
        </div>
      </div>
      
      <el-empty v-if="recordList.length === 0" description="暂无评估记录，请先进行创业能力评估"></el-empty>
      
      <div v-else class="record-list">
        <div v-for="(record, index) in recordList" :key="index" class="record-card">
          
          <div class="record-content">
            <div class="info-section">
              <h4>基本信息</h4>
              <div class="info-grid">
                <div class="info-item">
                  <span class="label">学号:</span>
                  <span class="value">{{ record.xuehao }}</span>
                </div>
                <div class="info-item">
                  <span class="label">姓名:</span>
                  <span class="value">{{ userForm.xueshengxingming }}</span>
                </div>
                <div class="info-item">
                  <span class="label">专业:</span>
                  <span class="value">{{ userForm.zhuanye }}</span>
                </div>
                <div class="info-item">
                  <span class="label">创业领域:</span>
                  <span class="value">{{ userForm.chuangyelingyu }}</span>
                </div>
              </div>
            </div>
            
            <div class="assessment-section">
              <h4>评估结果</h4>
              <div class="rating-box">
                <span class="rating-label">综合评级:</span>
                <span class="rating-value" v-html="ratingHtmlMap[record.baogaoneirong] || '加载中...'"></span>
              </div>
              
              
              <div class="view-full-report">
                <el-button type="primary" @click="openFullReport(record)">查看完整报告</el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
      
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, computed, getCurrentInstance, nextTick } from 'vue'
  import { useStore } from 'vuex'
  import { useRoute, useRouter } from 'vue-router'
  import moment from 'moment'
  
  const store = useStore()
  const route = useRoute()
  const router = useRouter()
  const context = getCurrentInstance()?.appContext.config.globalProperties
  const userForm = ref({})
  const recordList = ref([])
  const reportDialogVisible = ref(false)
  const currentReport = ref(null)
  const centerType = computed(() => route.query.centerType)
  // 标记是否正在查看他人的档案
  const isViewingOther = ref(false)
  // 新增：用于存储每个报告的评级HTML
  const ratingHtmlMap = ref({})

  const fetchRatingHtml = async (record) => {
    if (!record.baogaoneirong) return
    // 拼接完整URL
    const staticPrefix = 'http://localhost:8080/cl29556703/'
    const url = staticPrefix + record.baogaoneirong.replace(/^\/*/, '')
    try {
      const res = await fetch(url)
      const html = await res.text()
      // 用正则提取 <div class="evaluation-badge">...</div>
      const match = html.match(/<div class=\"evaluation-badge\"[^>]*>[\s\S]*?<\/div>/)
      if (match) {
        ratingHtmlMap.value[record.baogaoneirong] = match[0]
      } else {
        ratingHtmlMap.value[record.baogaoneirong] = '未评级'
      }
    } catch (e) {
      ratingHtmlMap.value[record.baogaoneirong] = '未评级'
    }
  }

  const fetchAllRatings = async () => {
    await nextTick()
    for (const record of recordList.value) {
      fetchRatingHtml(record)
    }
  }
  
  // 获取用户信息
  const getSession = () => {
    // 从localStorage中获取要查看的学生学号
    const storedXuehao = localStorage.getItem('viewStudentXuehao')
    
    if (storedXuehao) {
      // 如果有存储的学号，则获取该学号对应的用户信息
      context?.$http({
        url: 'chuangyezhe/query',
        method: 'get',
        params: {
          xuehao: storedXuehao
        }
      }).then(res => {
        if (res.data && res.data.code === 0 && res.data.data) {
          userForm.value = res.data.data
          // 标记为查看他人档案模式
          isViewingOther.value = true
          // 获取评估记录
          getRecords()
          // 使用完后清除localStorage中的学号，防止影响后续操作
          localStorage.removeItem('viewStudentXuehao')
        } else {
          context?.$toolUtil.message('未找到该学号对应的用户信息', 'error')
          // 清除localStorage并获取当前用户信息
          localStorage.removeItem('viewStudentXuehao')
          getCurrentUserInfo()
        }
      }).catch(() => {
        context?.$toolUtil.message('获取用户信息失败', 'error')
        // 清除localStorage并获取当前用户信息
        localStorage.removeItem('viewStudentXuehao')
        getCurrentUserInfo()
      })
    } else {
      // 否则获取当前登录用户的信息
      getCurrentUserInfo()
    }
  }
  
  // 获取当前登录用户信息
  const getCurrentUserInfo = () => {
    context?.$http({
      url: `${context?.$toolUtil.storageGet('frontSessionTable')}/session`,
      method: 'get'
    }).then(res => {
      if (res.data && res.data.data) {
        userForm.value = res.data.data
        isViewingOther.value = false
        // 获取评估记录
        getRecords()
      }
    })
  }
  
  // 获取评估记录
  const getRecords = () => {
    // 使用当前加载的用户学号
    const xuehaoToUse = userForm.value.xuehao
    
    if (!xuehaoToUse) return
    
    context?.$http({
      url: 'aipersonal/page',
      method: 'get',
      params: {
        page: 1,
        limit: 10,
        sort: 'shengchengshijian',
        order: 'desc',
        xuehao: xuehaoToUse
      }
    }).then(res => {
      if (res.data && res.data.code === 0) {
        recordList.value = res.data.data.list || []
        fetchAllRatings() // 新增
      }
    })
  }
  
  // 根据评级返回对应的CSS类
  const getRatingClass = (rating) => {
    if (!rating) return 'rating-none'
    
    if (rating.startsWith('S')) return 'rating-s'
    if (rating.startsWith('A')) return 'rating-a'
    if (rating.startsWith('B')) return 'rating-b'
    if (rating.startsWith('C')) return 'rating-c'
    return 'rating-d'
  }
  
  // 格式化日期
  const formatDate = (dateStr) => {
    if (!dateStr) return '未知时间'
    return moment(dateStr).format('YYYY-MM-DD HH:mm')
  }
  
  // 从报告中提取评级（S/A/B/C/D）
  const extractRating = (content) => {
    if (!content) return null
    
    // 尝试匹配评级格式
    const ratingMatch = content.match(/综合评级[：:]\s*([SABCD][\+\-]?)/i)
    if (ratingMatch && ratingMatch[1]) {
      return ratingMatch[1].toUpperCase()
    }
    
    return null
  }
  
  // 查看完整报告
  const viewFullReport = (record) => {
    currentReport.value = record
    reportDialogVisible.value = true
  }

  const openFullReport = (record) => {
  if (record.baogaoneirong) {
    // 新开标签页打开静态HTML页面
    const staticPrefix = 'http://localhost:8080/cl29556703/';
    window.open(staticPrefix + record.baogaoneirong.replace(/^\/*/, ''), '_blank');
  } else {
    context?.$toolUtil.message('报告文件不存在', 'error')
  }
}
  // 格式化报告内容
  const formatAnalysisContent = (content) => {
    if (!content) return ''
    
    try {
      // 移除干扰标记
      content = content.replace(/###+ \d+[\s\S]*?[，。：]、/g, '')
      
      // 移除多余的空行，只保留单个换行
      content = content.replace(/\n\s*\n+/g, '\n')
      
      // 处理标题和段落 (先处理这些，以便保留格式)
      content = content
        .replace(/### (.*?)(?:\r?\n|$)/g, '<h3>$1</h3>')
        .replace(/## (.*?)(?:\r?\n|$)/g, '<h2>$1</h2>')
        .replace(/# (.*?)(?:\r?\n|$)/g, '<h1>$1</h1>')
        .replace(/\r?\n\r?\n/g, '<br/>')
        .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
        .replace(/\*(.*?)\*/g, '<em>$1</em>')
        .replace(/---/g, '<hr>')
        
      // 处理列表 - 修改为不使用圆点的列表样式
      content = content
        .replace(/- (.*?)(?:\r?\n|$)/g, '<li style="list-style-type: none;">$1</li>')
        .replace(/• (.*?)(?:\r?\n|$)/g, '<li style="list-style-type: none;">$1</li>')
        .replace(/· (.*?)(?:\r?\n|$)/g, '<li style="list-style-type: none;">$1</li>')
        .replace(/○ (.*?)(?:\r?\n|$)/g, '<li style="list-style-type: none;">$1</li>')
        .replace(/● (.*?)(?:\r?\n|$)/g, '<li style="list-style-type: none;">$1</li>')
        .replace(/(\d+)\. (.*?)(?:\r?\n|$)/g, '<li style="list-style-type: none;">$1. $2</li>')
      
      content = content.replace(/(<li.*?<\/li>)+/g, '<ul style="list-style-type: none;">$&</ul>')
      
      // 移除所有剩余的Markdown符号
      content = content.replace(/#/g, '') // 移除所有井号
      content = content.replace(/\*/g, '') // 移除所有星号
      content = content.replace(/•/g, '') // 移除所有圆点
      content = content.replace(/·/g, '') // 移除所有间隔点
      content = content.replace(/○/g, '') // 移除所有空心圆
      content = content.replace(/●/g, '') // 移除所有实心圆
      content = content.replace(/^-\s+/gm, '') // 移除独立的-符号
      content = content.replace(/^\.\s+/gm, '') // 移除独立的.符号
      
      // 将单个换行替换为空格，使文本更紧凑
      content = content.replace(/\r?\n(?!\r?\n)/g, ' ')
      
      return content
    } catch (e) {
      console.error('格式化内容出错:', e)
      return content
    }
  }
  
  // 返回首页
  const goToHome = () => {
    router.push('/index/home')
  }
  
  // 返回个人中心或上一页
  const goToCenter = () => {
    // 如果是查看他人档案，则返回上一页
    if (isViewingOther.value) {
      router.go(-1)
    } else {
      // 否则返回个人中心
      router.push('/index/chuangyezheCenter')
    }
  }
  onMounted(() => {
    getSession()
  })
  </script>
  
  <style scoped>
  .pingding-records {
    padding: 20px;
  }
  
  .records-header {
    text-align: center;
    margin-bottom: 30px;
  }
  
  .records-header h2 {
    color: var(--theme);
    font-size: 24px;
    margin-bottom: 10px;
  }
  
  .subtitle {
    color: #666;
    font-size: 14px;
    margin-bottom: 20px;
  }

  /* 导航按钮样式 */
  .navigation-buttons {
    display: flex;
    justify-content: center;
    gap: 20px;
    margin-top: 20px;
  }
  
  .record-list {
    max-width: 1000px;
    margin: 0 auto;
  }
  
  .record-card {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
    overflow: hidden;
  }
  
  .record-header {
    background: #f5f5f5;
    padding: 15px 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #eee;
  }
  
  .record-title {
    display: flex;
    align-items: center;
  }
  
  .record-number {
    background: var(--theme);
    color: white;
    width: 30px;
    height: 30px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 10px;
    font-weight: bold;
  }
  
  .record-header h3 {
    margin: 0;
    font-size: 18px;
    color: #333;
  }
  
  .record-date {
    color: #999;
    font-size: 14px;
  }
  
  .record-content {
    padding: 20px;
  }
  
  .info-section, .assessment-section {
    margin-bottom: 20px;
  }
  
  .info-section h4, .assessment-section h4 {
    font-size: 16px;
    color: #333;
    margin-bottom: 15px;
    padding-left: 10px;
    border-left: 4px solid var(--theme);
  }
  
  .info-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 15px;
  }
  
  .info-item {
    display: flex;
  }
  
  .label {
    font-weight: bold;
    margin-right: 10px;
    color: #666;
    width: 80px;
  }
  
  .value {
    color: #333;
  }
  
  .rating-box {
    background: #f9f9f9;
    padding: 15px;
    border-radius: 5px;
    display: flex;
    align-items: center;
    margin-bottom: 20px;
  }
  
  .rating-label {
    font-weight: bold;
    margin-right: 10px;
  }
  
  .rating-value {
    font-size: 20px;
    font-weight: bold;
    padding: 5px 15px;
    border-radius: 4px;
  }
  
  .rating-s {
    color: #f56c6c;
    background-color: rgba(245, 108, 108, 0.1);
  }
  
  .rating-a {
    color: #e6a23c;
    background-color: rgba(230, 162, 60, 0.1);
  }
  
  .rating-b {
    color: #409eff;
    background-color: rgba(64, 158, 255, 0.1);
  }
  
  .rating-c {
    color: #67c23a;
    background-color: rgba(103, 194, 58, 0.1);
  }
  
  .rating-d {
    color: #909399;
    background-color: rgba(144, 147, 153, 0.1);
  }
  
  .rating-none {
    color: #909399;
    background-color: #f5f5f5;
  }
  
  .analysis-content {
    max-height: 200px;
    overflow-y: auto;
    padding: 10px;
    background: #f9f9f9;
    border-radius: 5px;
    margin-bottom: 20px;
  }
  
  .view-full-report {
    text-align: center;
  }
  
  .full-report {
    max-height: 70vh;
    overflow-y: auto;
  }
  
  .report-content {
    padding: 20px;
  }
  
  .report-content :deep(h1) {
    font-size: 22px;
    color: var(--theme);
    margin: 20px 0 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #eee;
  }
  
  .report-content :deep(h2) {
    font-size: 20px;
    color: #333;
    margin: 18px 0 12px;
  }
  
  .report-content :deep(h3) {
    font-size: 18px;
    color: #333;
    margin: 15px 0 10px;
    padding-left: 10px;
    border-left: 4px solid var(--theme);
  }
  
  .report-content :deep(strong) {
    font-weight: bold;
    color: #333;
  }
  
  .report-content :deep(ul) {
    padding-left: 20px;
  }
  </style>